#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File ：LoginMiddleware.py
@Author ：zqy
@Email : zqingy@work@163.com
@note: 登录相关中间件
"""
from functools import wraps
from typing import Any

from flask import request, session, g

from application.config.ServerConfig import ServerConfig
from application.enumeration.StatusCodeEnum import StatusCodeEnum
from application.exception.BasicException import BasicException
from application.mapper.UserMapper import UserMapper
from application.util.TokenUtil import verify_token, get_user_id


def login_required(func: Any) -> Any:
    @wraps(wrapped=func)
    def wrapper(*args, **kwargs) -> Any:
        try:
            # 过滤掉Bearer 前缀
            token: str = request.headers.get(ServerConfig.token_name)
            if "Bearer" in token:
                token = token.split("Bearer ")[1]
            # 验证用户Token
            if not token or not verify_token(token=token):
                raise BasicException(status_code=StatusCodeEnum.AUTHORITY_ERROR.value,
                                     error_message="非法访问，请先登录")
            # 存储Token到session
            session["user"] = get_user_id(token=token)
            g.user = UserMapper.get_info_by_id(model_id=session["user"])
            session.permanent = True  # 设置session永久有效，除非被删除
            return func(*args, **kwargs)
        except IndexError:
            raise BasicException(status_code=StatusCodeEnum.AUTHORITY_ERROR.value, error_message="Token格式错误")
        except AttributeError:
            raise BasicException(status_code=StatusCodeEnum.AUTHORITY_ERROR.value,
                                 error_message=f"缺少{ServerConfig.token_name}")

    return wrapper
